package com.example.search.controller;

import com.example.common.util.R;
import com.example.common.util.ResultCodeRecord;
import com.example.model.search.dto.UserSearchDto;
import com.example.search.pojo.AssociateWords;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/api/v1/")
@Tag(name = "搜索联想词管理")
@Slf4j
public class AssociateWordsController {
    @Autowired
    private MongoTemplate mongoTemplate;

    @PostMapping(value = "/associate/search/{page}/{pageSize}")
    @Operation(summary = "搜索联想词")
    public R search(@RequestBody UserSearchDto userSearchDto, @PathVariable(value = "page") Long page, @PathVariable(value = "pageSize") Long pageSize) {
        // 1、检查参数
        if (StringUtils.isBlank(userSearchDto.getSearchWords())) {
            return R.error(ResultCodeRecord.PARAM_INVALID);
        }

        // 2、分页检查
        if (page < 1 || pageSize < 1) {
            return R.error("分页参数无效");
        }

        // 3、执行查询，模糊查询
        Query query = Query.query(Criteria.where("associateWords").regex("^.*" + Pattern.quote(userSearchDto.getSearchWords()) + ".*$"));

        // 计算总记录数
        long total = mongoTemplate.count(query, AssociateWords.class);

        // 添加分页参数
        query.skip((page - 1) * pageSize).limit(pageSize.intValue());

        // 执行查询
        List<AssociateWords> associateWordsList = mongoTemplate.find(query, AssociateWords.class);

        // 计算总页数
        long pages = (total + pageSize - 1) / pageSize;

        // 构建响应数据
        Map<String, Object> map = new HashMap<>();
        map.put("total", total);
        map.put("pageSize", pageSize);
        map.put("pages", pages);
        map.put("page", page);
        map.put("associateWordsList", associateWordsList);

        if (!associateWordsList.isEmpty()) {
            return R.ok("搜索联想词成功").data(map);
        } else {
            return R.error("搜索联想词失败");
        }
    }
}
